// Pages/order/order.js
import {Order} from "./order_model.js";
import {Cart} from "../cart/cart_model.js";
import {Address} from "../../utils/address.js";

var order = new Order;
var cart = new Cart;
var address = new Address;

Page({

  /**
   * 页面的初始数据
   */
  data: {
     account:null,//商品总额
     id: null, //订单编号
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     var productsArr;
     this.data.account = options.account;
     var productsArr = cart._getLocalStorageData(true);
     this.setData({
        productsArr:productsArr,
        account:this.data.account,
        orderStatus:0
     }); 
     //获取服务器的地址
     address.getAddress((res) => {
        this._bindAddressInfo(res);
     });
  },
  onShow:function(){
     if(this.data.id){
        var that = this;
        //下单后，支付成功或者失败后，点左上角返回时能够更新订单状态以放在onshow中
         var id = this.data.id;
         order.getOrderInfoById(id, (data) => {
            that.setData({
               orderStatus: data.status,
               productsArr: data.snap_items,
               account: data.total_price,
               basicInfo:{
                  orderTime:data.create_time,
                  orderNo: data.order_no
               }
            });
            //快照地址
            var addressInfo = data.snap_address;
            addressInfo.totalDetail = address.setAddressInfo(addressInfo);
            that._bindAddressInfo(addressInfo);
         });
     }
  },
   //添加地址
  editAddress:function(){
     var that = this;
     wx.chooseAddress({
        success:function(res){
           var addressInfo = {
              name: res.userName,
              mobile:res.telNumber,
              totalDetail: address.setAddressInfo(res)
           };
         
           that._bindAddressInfo(addressInfo);
           //把址写入数据库
           address.submitAddress(res, (flag) => {
              if(!flag){
                 that.showTips('操作提示', '地址更新失败', flag);
              }else{
                 that.showTips('操作成功', '地址更新成功', flag);
              }
           })
        }
     });
  },
  //提示的小弹框
  showTips(title,content,flag){
     wx.showModal({
        title: title,
        content: content,
        showCancel: false,
        success:function(res){
           if(flag){
              wx.switchTab({
                 url: '/Pages/my/my',
              })
           }
        }
     })
  },
  //数据绑定
  _bindAddressInfo:function(addressInfo){
     this.setData({
        addressInfo:addressInfo
     })
  },
  //向微信服务器发送支付请求
  pay:function(){
     if(!this.data.addressInfo){
        this.showTips('下单提示！', '请您填写您的收货地址！');
        return;
     }
     if(this.data.orderStatus == 0){
        this._firstTimePay();
     }else{
        tihs._oneMoreTimePay();
     }
  },
  //第一次向服务器发送请求，生成订单号
  _firstTimePay:function(){
     let orderInfo = [];
     let productInfo = this.data.productsArr;
     let length = productInfo.length;
     for(let i = 0; i < length; i++){
        orderInfo.push({
           product_id: productInfo[i].id,
           count:productInfo[i].counts
        });
     }

     var that = this;
     //支付分两步，第一步是生成订单号，然后根据订单号支付
     order.doOrder(orderInfo, (data) => {
        if(data.pass){
           var id = data.order_id;
           that.data.id = id;
           that.data.fromCartFlag = false;
           //开始支付
           that._execPay(id);
        }else{
           that._orderFail(data);//下单失败
        }
     })
  },
  //下单失败后的提示信息
  _orderFail:function(data){
     var nameArr = [], name = '', str = '', pArr = data.pStatusArray;
     let length = pStatusArray.length;
     for(let i = 0; i < length; i++){
        if(!pArr[i].haveStock){
           name = pArr[i].name;
           if(name.length > 15){
              name = name.substr(0, 12) + '...';
           }
           nameArr.push(name);
           if(nameArr.length >= 2){
              break;
           }
        }
     }
     str += nameArr.join('、');
     if(nameArr.length > 2){
        str += '等';
     }
     str += '缺货';
     wx.showModal({
        title: '下单失败',
        content: str,
        showCancel: false,
        success:function(res){}
     });
  },
  //执行支付
  _execPay:function(orderNumber){
     var that = this;
     order.execPay(orderNumber, (statusCode) => {
        if(statusCode != 0){
           that.deleteProducts();//删除购物车的商品
           var flag = statusCode == 2;//支付成功的标识
           wx.navigateTo({
              url: "../pay-result/pay-result?id=" + orderNumber + "&flag=" + flag + "&from=order"
           });
        }
     });
  },
  //删除购物车内的商品
  deleteProducts:function(){
     var ids = [], arr = this.data.productsArr;
     let length = arr.length;
     for(let i = 0; i < length; i++){
        ids.push(arr[i].id);
     }
     cart.delete(ids);
  }
})